package com.project.school_flate.config.tableListener;

import cn.hutool.core.date.DateUtil;
import com.mybatisflex.annotation.SetListener;
import com.project.school_flate.entity.com.ComFileDetail;
import com.project.school_flate.service.com.ComFileDetailService;
import com.project.school_flate.util.PoToDTO;
import org.apache.commons.lang3.StringUtils;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@Component
public class ComFileDetailListener implements SetListener {

    public static ComFileDetailListener oComFileDetailListener;

    @Autowired
    private FileStorageService fileStorageService;

    @PostConstruct
    public void init() {
        oComFileDetailListener = this;
        oComFileDetailListener.fileStorageService = this.fileStorageService;
    }

    @Override
    public Object onSet(Object entity, String property, Object value) {
        if("createTime".equals(property)){
            try {
                ComFileDetail oComFileDetail = (ComFileDetail) entity;
                if(StringUtils.isBlank(oComFileDetail.getGenerateUrl())){
                    FileInfo oFileInfo = new FileInfo();
                    PoToDTO.poToDto(oComFileDetail,oFileInfo);
                    String url = oComFileDetailListener.fileStorageService.generatePresignedUrl(oFileInfo, DateUtil.offsetHour(new Date(),1));
                    oComFileDetail.setGenerateUrl(url);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return value;
    }

}